package com.chushouya.config;

import org.springframework.boot.web.servlet.error.ErrorController;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;

/**
 * 全局错误处理器
 * 替换 Spring Boot 默认的 Whitelabel Error Page，返回 JSON 格式的错误信息
 */
@RestController
public class GlobalErrorHandler implements ErrorController {

    private static final String ERROR_PATH = "/error";

    @RequestMapping(value = ERROR_PATH)
    public ResponseEntity<Map<String, Object>> error(HttpServletRequest request) {
        Map<String, Object> errorResponse = new HashMap<>();
        
        // 获取错误状态码
        Integer statusCode = (Integer) request.getAttribute("javax.servlet.error.status_code");
        if (statusCode == null) {
            statusCode = 500;
        }
        
        // 获取错误信息
        String errorMessage = (String) request.getAttribute("javax.servlet.error.message");
        if (errorMessage == null || errorMessage.isEmpty()) {
            errorMessage = getDefaultErrorMessage(statusCode);
        }
        
        // 获取请求路径
        String requestUri = (String) request.getAttribute("javax.servlet.error.request_uri");
        if (requestUri == null) {
            requestUri = request.getRequestURI();
        }
        
        // 构建错误响应
//        errorResponse.put("success", false);
        errorResponse.put("code", statusCode);
        errorResponse.put("message", errorMessage);
//        errorResponse.put("path", requestUri);
//        errorResponse.put("timestamp", LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        
        // 开发环境下可以添加更多调试信息
        if (isDevEnvironment()) {
            errorResponse.put("method", request.getMethod());
            errorResponse.put("userAgent", request.getHeader("User-Agent"));
        }
        
        return new ResponseEntity<>(errorResponse, HttpStatus.valueOf(statusCode));
    }
    
    /**
     * 获取默认错误信息
     */
    private String getDefaultErrorMessage(int statusCode) {
        switch (statusCode) {
            case 400:
                return "请求参数错误";
            case 401:
                return "未授权访问";
            case 403:
                return "禁止访问";
            case 404:
                return "请求的资源不存在";
            case 405:
                return "请求方法不被允许";
            case 500:
                return "服务器内部错误";
            case 502:
                return "网关错误";
            case 503:
                return "服务不可用";
            default:
                return "未知错误";
        }
    }
    
    /**
     * 判断是否为开发环境
     */
    private boolean isDevEnvironment() {
        String profile = System.getProperty("spring.profiles.active", "");
        return profile.contains("dev") || profile.contains("local");
    }
    
    @Override
    public String getErrorPath() {
        return ERROR_PATH;
    }
}
